﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Nuzzle.Protocol
{
    public class NetworkMessageReader
    {
        public BigEndianReader Reader;

        public uint Header;
        public NetworkMessageID ID;
        public uint TypeLen;
        public int PacketLenght;

        public NetworkMessageReader(BigEndianReader reader)
        {
            this.Reader = reader;
            this.Unpack();
        }

        public void Unpack()
        {
            this.Header = this.Reader.readUShort();
            this.ID = (NetworkMessageID)(Header >> 2);
            this.TypeLen = Header & 3;
            this.SetPacketLenght();
        }

        public void SetPacketLenght()
        {
            switch (TypeLen)
            {
                case 1:
                    PacketLenght = Reader.readByte();
                    break;

                case 2:
                    PacketLenght = (int)Reader.readUShort();
                    break;

                case 3:
                    PacketLenght = (int)((Reader.readByte() & 255) << 16) + ((Reader.readByte() & 255) << 8) + (Reader.readByte() & 255);
                    break;

                default:
                    PacketLenght = 0;
                    break;
            }
        }

        public int PacketTotalLenght
        {
            get
            {
                switch (TypeLen)
                {
                    case 1:
                        return PacketLenght + 3;

                    case 2:
                        return PacketLenght + 4;

                    case 3:
                        return PacketLenght + 9;

                    default:
                        return PacketLenght + 2;
                }
            }
        }
    }
}
